package com.xxxx.portal.interceptor;


import com.xxxx.common.pojo.Admin;
import com.xxxx.common.utils.CookieUtil;
import com.xxxx.sso.service.SSOService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @Author GP
 * @Date 2020/8/31 20:37
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Reference(interfaceClass = SSOService.class)
    private SSOService ssoService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${user.ticket}")
    private String userTicket;


    /**
     * 在请求处理的方法之前执行
     * 1、通过request获取 cookie中是否存在ticket票据
     * 有， 验证ticket是否失效；
     * 没失效就将用户信息存入session中，用于数据回显（在页面中显示用户信息）
     * 再重新设置失效时间
     * 无，重定向到登录页
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取cookie中的ticket
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //判断ticket是否为空
        if (StringUtils.isEmpty(ticket)) {
            //若ticket为空，重定向至登录页
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        //若不为空，验证ticket是否失效(若失效，方法里就会返回null)，没失效返回用户信息
        Admin admin = ssoService.VerifyTicket(ticket);
        if (!StringUtils.isEmpty(admin)) { //若存在用户信息，说明ticket未失效
            //将用户信息存入session中，用于数据回显；
            request.getSession().setAttribute("user", admin);
            System.out.println(admin);
//            //重新设置失效时间
//            ValueOperations value = redisTemplate.opsForValue();
//                System.out.println(userTicket);
//            value.set(userTicket+":"+ticket, JsonUtil.object2JsonStr(admin),30, TimeUnit.MINUTES);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
